require "digest/sha1"

class User < ActiveRecord::Base
  # Basic validations for required fields.  
  validates_presence_of :name, :email, :password, :password_confirmation
  validates_uniqueness_of :name, :email
  
  attr_accessor :password_confirmation
  validates_confirmation_of :password
  
  validates_size_of :name, :in => 4..16, :message => "Name length out of range."

  validates_format_of :email,
    :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i,
    :message => "Invalid email format!"
  validates_format_of :name,
    :with => /\w+/,
    :message => "Name format error, don't use special characters."
  
  def validate
    errors.add_to_base("Missing password.") if hashed_password.blank?
  end
  
  # Customized password accessor for password, to do encryption.
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    self.hashed_password = User.encrypted_password(self.password)
  end
  
  def self.authenticate(name, password)
    user = self.find_by_name(name)
    if user
      expected_password = encrypted_password(password)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end
  
  def display_name
    (nick_name.nil? or (nick_name.strip.length == 0)) ? name : nick_name
  end

  # Make this method public, so I can call it to implement
  # my own password confirmation function.
  
  # Password encryption. Based on "Agile web develop".
  # remove the 'salt' part for simplicity.
  def self.encrypted_password(password)
    string_to_hash = password + "microblog"
    # microblog is added for harder guessing
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  
end
